#爬取bing背景图
#coding:utf-8
import urllib.request
import requests
import re
import os
import datetime
baseurl="https://cn.bing.com"
imagePath="python/python.robot/image/"

#获取页面内容
def getPageHtml(url,decode='utf-8'):
    res=urllib.request.urlopen(url)
    html=res.read().decode('utf-8')
    return html

#正则匹配图片路径
def getImageUrl(html):
    pattern=re.compile(r'id="bgLink".*?href="([\s\S].*?)"',re.S)
    source= pattern.findall(html)
    result=baseurl+source[0]
    print(result)
    return result

#保存图片在本地
def saveImage(imageUrl):
    if not os.path.exists(imagePath):
        os.makedirs(imagePath)

    pic=requests.get(imageUrl)
    curdate=datetime.datetime.now()
    file_name = imagePath+str(curdate.year)+str(curdate.month)+str(curdate.day)+".jpg" #拼接图片名
    print(file_name)
    #将图片存入本地
    fp = open(file_name,'wb')
    fp.write(pic.content) #写入图片
    fp.close()


htmlstr= getPageHtml(baseurl)
picUrl=getImageUrl(htmlstr)
saveImage(picUrl)






